/*
* © 2010 Autodata Solutions Company. All Rights Reserved
* This source code is the confidential and proprietary information of Autodata Solutions Company.
* The user shall not, in whole or in part, copy, publish, disclose or make any use of this source code
* without the prior written consent of Autodata Solutions Company.
*
* File: net/autodata/compare/widgets/ResultsGridToolbar.js
* Purpose: Provides custom implimintation of the compare result grid's top toolbar.
*
* Namespace: net.autodata.compare
* Requires:ExtJS,
*          ASC library - net/autodata/ascjs-ext-debug.js
*/

Ext.ns('net.autodata.compare.ResultsGridToolbar');
(function() {
    /*
    * On Proxy load event handler, which retrieves the raw response in order 
    * to retrieve the groupMapping node.
    * @param {Ext.data.Store} store Store object
    * @param {Object} response JSON response from the proxy ajax call
    * @options {Objects} Proxy on load json options.
    */
    function onProxyLoad(store, response, options) {
        if (response !== null && response.groupMapping !== null) {
            response = response.groupMapping;
            this.data = new Ext.util.MixedCollection(false);
            for (var x = 0; x < response.length; ++x) {
                var group = response[x];
                if (group != null) {
                    var subGroups = [];
                    for (var y = 0; y < group.subGroups.length; ++y) {
                        var sub = group.subGroups[y];
                        if (sub != null && sub.ID != null) {
                            subGroups.push(sub.ID);
                        }
                    }
                    this.data.add(group.description, { regex: new RegExp('^' + subGroups.join('|') + '$', 'i'), order: group.sortOrder });
                }
            }
        }

        if (this.data &&
            this.data instanceof Ext.util.MixedCollection &&
            this.data.getCount() > 0) {
            this.data.sort("ASC", function(a, b) {
                return a.order - b.order;
            });
        }

        if (!this.rendered) {
            return;
        }

        this.buildComponents();
    }

    var toggleGroup = Ext.id(undefined, 'results-filter-selector-btns');

    /**
    * Custom toolbar plugin for grid top toolbar
    * @class ResultToolbar
    * @extends Ext.Toolbar
    * @namespace net.autodata.compare 
    */
    var Toolbar = Ext.extend(Ext.Toolbar, {
        grid: undefined,
        data: undefined,
        forceLayout: true,
        border: false,
        width: 788,
        height: 35,
        activeGroup: undefined,
        cls: 'compare-toolbar',

        constructor: function(cfg) {
            Toolbar.superclass.constructor.call(this, cfg);
        },

        /**
        * Toolbar's plugin initilaization function.
        * @method init
        * @param {net.autodata.compare.ResultsGrid} grid
        */
        init: function(grid) {
            this.grid = grid;
            this.grid.on({
                'destroy': this.onDestroy,
                scope: this
            });

            var store = this.grid.getStore();
            if (store !== null && store.proxy !== null) {
                store.proxy.addListener('load', onProxyLoad, this);
            }

            store.on('load', this.onAfterStoreLoad, this);
        },

        /**
        * Turns off the button toggled property on all toolbar buttons.
        * @method triggerCollapseExpand
        * @param {boolean} op True/False value of whther to collapse the grid.
        */
        triggerCollapseExpand: function(op) {
            if (this.grid != null) {
                var view = this.grid.getView();
                if (view != null &&
                    view.collapseAllGroups &&
                    view.expandAllGroups) {
                    if (op) {
                        view.collapseAllGroups();
                    } else {
                        view.expandAllGroups();
                    }
                }
            }
        },

        /**
        * Builds toolbar's inner components.
        * @method buildComponents
        */
        buildComponents: function() {
            this.removeAll(true);

            var tm = null;
            
            if (ASC.cfg.getLocale().language.toUpperCase() != 'EN' && (Ext.isIE7 || Ext.isIE6)) {
                tm = Ext.util.TextMetrics.createInstance(Ext.getBody());
            }

            if (this.data !== undefined) {
                this.data.eachKey(function(key, value) {
                    if (value && value.regex) {
                        if (this.activeGroup === undefined) {
                            this.activeGroup = key;
                        }

                        var cfg = {
                            xtype: 'a-btn-toolbar',
                            text: key,
                            itemId: key,
                            hide: false,
                            toggleGroup: toggleGroup,
                            listeners: {
                                'click': this.onButtonClick.createDelegate(this, [key, value.regex], 1)
                            }
                        };
                        
                        if (tm) {
                            var width = tm.getWidth(key);
                            if(width && ASC.util.isNumeric(width) && width > 0) {
                                Ext.apply(cfg, {
                                    width: width + 16
                                });
                            }
                        }

                        this.addButton(cfg);
                    }
                }, this);
            }

            this.addFill();

            var collapseAllText = ASC.message('net.autodata.compare.toolbar.label.collapse-all');
            var expandAllText = ASC.message('net.autodata.compare.toolbar.label.expand-all');

            this.addButton({
                ctCls: 'compare-btn-wrap',
                cls: 'x-btn-text-icon',
                iconCls: 'btn-expand-icon',
                iconAlign: 'right',
                text: expandAllText,
                handleMouseEvents: false,
                handler: this.triggerCollapseExpand.createDelegate(this, false, 0)
            });

            this.addButton({
                ctCls: 'compare-btn-wrap',
                cls: 'x-btn-text-icon',
                iconCls: 'btn-collapse-icon',
                iconAlign: 'right',
                text: collapseAllText,
                handleMouseEvents: false,
                handler: this.triggerCollapseExpand.createDelegate(this, true, 0)
            });

            if (this.boxReady) {
                this.doLayout(false, true);
            }
        },

        //Event Handlers

        /**
        * Store load's event handler that applies a filter after the store loads.
        * @method onAfterStoreLoad
        * @param {Ext.data.Store} store Parent grid's store object
        * @param {RegEx} filter Regular expression to filter on
        * @private
        */
        onAfterStoreLoad: function() {
            if (this.activeGroup !== undefined) {
                var button = this.getComponent(this.activeGroup);
                if (button != undefined) {
                    var value = this.data.key(this.activeGroup);
                    if (value != null) {
                        this.onButtonClick(button, this.activeGroup, value.regex);
                        button.toggle(true, true);
                    }
                }
            }
        },

        /**
        * Store load's event handler that applies a filter after the store loads.
        * @method onButtonClick
        * @param {Ext.Button} button Ext Button object that triggered the click event.
        * @param {string} groupID The groupID name.
        * @param (RegEx) filter The regular expression filter.
        * @private
        */
        onButtonClick: function(button, groupID, filter) {
            if (button) {
                button.toggle(true, false);
            }

            if (filter !== null) {
                var store = this.grid.getStore();
                if (store !== null &&
                    store.filter) {
                    store.filter('groupID', filter);
                    this.activeGroup = groupID;
                    return;
                }
            }

            this.data.removeKey(groupID);
        },

        /**
        * Toolbar's on render event handler.
        * @method onRender
        * @private
        */
        onRender: function() {
            Toolbar.superclass.onRender.apply(this, arguments);
            this.buildComponents();
        },

        /**
        * Toolbars on destroy event handler.
        * @method onDestroy
        * @private
        */
        onDestroy: function() {
            //clean up to ensure no function references are left behind
            //to cause a memmory leak
            this.grid.un('destroy', this.onDestroy, this);

            var store = this.grid.getStore();
            if (store !== null && store.proxy !== null) {
                store.proxy.un('load', onProxyLoad, store.proxy);
            }
            store.un('load', this.onAfterStoreLoad, this);

            delete this.data;
            this.removeAll(true);
        }
    });

    net.autodata.compare.ResultsGridToolbar = Toolbar;
})();
